﻿using Lion.WeiXin.Core.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Lion.WeiXin.Core.Data
{
   public class DictionaryDAO :IDictionary
    {
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(Models.DictionaryModel model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into T_Dictionary(");
            strSql.Append("Dic_Key,Dic_Value,Parameter,Parameter2,Creator,Remark,Last_Changed_By,IsDelete)");
            strSql.Append(" values (");
            strSql.Append("@Dic_Key,@Dic_Value,@Parameter,@Parameter2,@Creator,@Remark,@Last_Changed_By,@IsDelete)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@Dic_Key", SqlDbType.VarChar,12),
					new SqlParameter("@Dic_Value", SqlDbType.VarChar,200),
					new SqlParameter("@Parameter", SqlDbType.VarChar,200),
                    new SqlParameter("@Parameter2", SqlDbType.VarChar,200),
					new SqlParameter("@Creator", SqlDbType.VarChar,50),
					new SqlParameter("@Remark", SqlDbType.VarChar,200),
                    new SqlParameter("@Last_Changed_By", SqlDbType.VarChar,50),
                    new SqlParameter("@IsDelete", SqlDbType.Int,4) };
            parameters[0].Value = model.Dic_Key;
            parameters[1].Value = model.Dic_Value;
            parameters[2].Value = model.Parameter;
            parameters[3].Value = model.Parameter2;
            parameters[4].Value = model.Creator;
            parameters[5].Value = model.Remark;
            parameters[6].Value = model.Last_Changed_By;
            parameters[7].Value = model.IsDelete;


            object obj = SqlHelper.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(Models.DictionaryModel model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update T_Dictionary set ");
            strSql.Append("Dic_Key=@Dic_Key,");
            strSql.Append("Dic_Value=@Dic_Value,");
            strSql.Append("Parameter=@Parameter,");
            strSql.Append("Parameter2=@Parameter2,");
            strSql.Append("LastUpdateDate=@LastUpdateDate,");
            strSql.Append("Creator=@Creator,");
            strSql.Append("Remark=@Remark,");
            strSql.Append("Last_Changed_By=@Last_Changed_By,");
            strSql.Append("IsDelete=@IsDelete");
            strSql.Append(" where AID=@AID");
            SqlParameter[] parameters = {
					new SqlParameter("@Dic_Key", SqlDbType.VarChar,12),
					new SqlParameter("@Dic_Value", SqlDbType.VarChar,200),
					new SqlParameter("@Parameter", SqlDbType.VarChar,200),
                    new SqlParameter("@Parameter2", SqlDbType.VarChar,200),
					new SqlParameter("@LastUpdateDate", SqlDbType.DateTime),
					new SqlParameter("@Creator", SqlDbType.VarChar,50),
					new SqlParameter("@Remark", SqlDbType.VarChar,1000),
                    new SqlParameter("@Last_Changed_By", SqlDbType.VarChar,50),
                    new SqlParameter("@IsDelete", SqlDbType.Int,4),
					new SqlParameter("@AID", SqlDbType.Int,4)};
            parameters[0].Value = model.Dic_Key;
            parameters[1].Value = model.Dic_Value;
            parameters[2].Value = model.Parameter;
            parameters[3].Value = model.Parameter2;
            parameters[4].Value = model.LastUpdateDate;
            parameters[5].Value = model.Creator;
            parameters[6].Value = model.Remark;
            parameters[7].Value = model.Last_Changed_By;
            parameters[8].Value = model.IsDelete ;
            parameters[9].Value = model.AID;

            int rows = SqlHelper.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int AID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from T_Dictionary ");
            strSql.Append(" where AID=@AID");
            SqlParameter[] parameters = {
					new SqlParameter("@AID", SqlDbType.Int,4)
			};
            parameters[0].Value = AID;

            int rows = SqlHelper.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string AIDlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from T_Dictionary ");
            strSql.Append(" where AID in (" + AIDlist + ")  ");
            int rows = SqlHelper.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool DeleteLogic(string ids)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update T_Dictionary set IsDelete=1");
            strSql.Append(" where AID in (" + ids + ")  ");
            int rows = SqlHelper.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Models.DictionaryModel GetModel(int AID)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 AID,Dic_Key,Dic_Value,Parameter,Parameter2,CreateDate,LastUpdateDate,Creator,Remark,Last_Changed_By,IsDelete from T_Dictionary ");
            strSql.Append(" where AID=@AID");
            SqlParameter[] parameters = {
					new SqlParameter("@AID", SqlDbType.Int,4)
			};
            parameters[0].Value = AID;

            Models.DictionaryModel model = new Models.DictionaryModel();
            DataSet ds = SqlHelper.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return ConvertToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Models.DictionaryModel GetModel(string dicKey)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 AID,Dic_Key,Dic_Value,Parameter,Parameter2,CreateDate,LastUpdateDate,Creator,Remark,Last_Changed_By,IsDelete from T_Dictionary ");
            strSql.Append(" where Dic_Key=@Dic_Key");
            SqlParameter[] parameters = {
					new SqlParameter("@Dic_Key", SqlDbType.VarChar,12)
			};
            parameters[0].Value = dicKey;

            Models.DictionaryModel model = new Models.DictionaryModel();
            DataSet ds = SqlHelper.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return ConvertToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Models.DictionaryModel ConvertToModel(DataRow row)
        {
            Models.DictionaryModel model = new Models.DictionaryModel();
            if (row != null)
            {
                if (row["AID"] != null && row["AID"].ToString() != "")
                {
                    model.AID = int.Parse(row["AID"].ToString());
                }
                if (row["Dic_Key"] != null)
                {
                    model.Dic_Key = row["Dic_Key"].ToString();
                }
                if (row["Dic_Value"] != null)
                {
                    model.Dic_Value = row["Dic_Value"].ToString();
                }
                if (row["Parameter"] != null)
                {
                    model.Parameter = row["Parameter"].ToString();
                }
                if (row["Parameter2"] != null)
                {
                    model.Parameter2 = row["Parameter2"].ToString();
                }
                if (row["CreateDate"] != null && row["CreateDate"].ToString() != "")
                {
                    model.CreateDate = DateTime.Parse(row["CreateDate"].ToString());
                }
                if (row["LastUpdateDate"] != null && row["LastUpdateDate"].ToString() != "")
                {
                    model.LastUpdateDate = DateTime.Parse(row["LastUpdateDate"].ToString());
                }
                if (row["Creator"] != null)
                {
                    model.Creator = row["Creator"].ToString();
                }
                if (row["Remark"] != null)
                {
                    model.Remark = row["Remark"].ToString();
                }
                if (row["Last_Changed_By"] != null)
                {
                    model.Last_Changed_By = row["Last_Changed_By"].ToString();
                }
                if (row["IsDelete"] != null)
                {
                    model.IsDelete = int.Parse(row["IsDelete"].ToString());
                }
            }
            return model;
        }

        protected List<Models.DictionaryModel> ConvertToList(DataSet ds)
        {
            List<Models.DictionaryModel> list = new List<Models.DictionaryModel>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                Models.DictionaryModel model = ConvertToModel(row);
                list.Add(model);
            }
            return list;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<Models.DictionaryModel> GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select AID,Dic_Key,Dic_Value,Parameter,Parameter2,CreateDate,LastUpdateDate,Creator,Remark,Last_Changed_By,IsDelete ");
            strSql.Append(" FROM T_Dictionary ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            DataSet ds = SqlHelper.Query(strSql.ToString());
            return ConvertToList(ds);
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public List<Models.DictionaryModel> GetList(int Top, string strWhere, string filedOrder)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ");
            if (Top > 0)
            {
                strSql.Append(" top " + Top.ToString());
            }
            strSql.Append(" AID,Dic_Key,Dic_Value,Parameter,Parameter2,CreateDate,LastUpdateDate,Creator,Remark,Last_Changed_By,IsDelete ");
            strSql.Append(" FROM T_Dictionary ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by " + filedOrder);
            DataSet ds = SqlHelper.Query(strSql.ToString());
            return ConvertToList(ds);
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM T_Dictionary ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = SqlHelper.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public List<Models.DictionaryModel> GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.AID desc");
            }
            strSql.Append(")AS Row, T.*  from T_Dictionary T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            DataSet ds = SqlHelper.Query(strSql.ToString());
            return ConvertToList(ds);
        }

        public List<Models.DictionaryModel> GetList(int PageSize, int PageIndex, string strWhere)
        {
            SqlParameter[] parameters = {
                    new SqlParameter("@tblName", SqlDbType.VarChar, 255),
                    new SqlParameter("@fldName", SqlDbType.VarChar, 255),
                    new SqlParameter("@PageSize", SqlDbType.Int),
                    new SqlParameter("@PageIndex", SqlDbType.Int),
                    new SqlParameter("@IsReCount", SqlDbType.Bit),
                    new SqlParameter("@OrderType", SqlDbType.Bit),
                    new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
                    };
            parameters[0].Value = "T_Dictionary";
            parameters[1].Value = "AID";
            parameters[2].Value = PageSize;
            parameters[3].Value = PageIndex;
            parameters[4].Value = 0;
            parameters[5].Value = 0;  //非0值就是降序
            parameters[6].Value = strWhere;
            DataSet ds = SqlHelper.RunProcedure("UP_GetRecordByPage", parameters, "ds");
            return ConvertToList(ds);
        }

        public string GetNewKey(string parentKey)
        {
            string newKey = string.Empty;
            List<DictionaryModel> list = GetList(string.Empty);
            //自动产生一个Key 键值
            if (parentKey == "000" && parentKey.Length == 3)
            {
                //自动产生一个一级子节点(3位一段)
                List<DictionaryModel> topDics = list.Where(n => n.Dic_Key.Length == 3).ToList();
                if (topDics.Count == 0)
                {
                    //数据库中无一条记录,所有子节点从100开始
                    newKey = "100";
                }
                else
                {
                    long maxKey = topDics.Max(n => long.Parse(n.Dic_Key));
                    newKey = (maxKey + 1).ToString();
                }
            }
            else
            {
                //查找当前节点的所有子节点，并且
                List<DictionaryModel> childDics = list.Where(n => n.Dic_Key.IndexOf(parentKey) == 0 && n.Dic_Key.Length== parentKey.Length+3).ToList();
                if (childDics.Count == 0)
                {
                    //无子节点 
                    newKey = parentKey + "001";
                }
                else
                {
                    long maxKey = childDics.Max(n => long.Parse(n.Dic_Key));
                    newKey = (maxKey + 1).ToString();
                }
            }
            return newKey;
        }
    }
}
